import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/home/column_type_enum.dart';
import 'package:hktk_app/ienum/my/rank_type_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/pages/mine/child/view_chapter_page.dart';
import 'package:hktk_app/pages/mine/child/view_page.dart';
import 'package:hktk_app/pages/mine/child/view_paper_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/widget/mine/my_tab_bar_widget.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';

/// 我的错题页面
class WrongQuestionPage extends StatefulWidget {
  const WrongQuestionPage({super.key});

  @override
  State<WrongQuestionPage> createState() => _WrongQuestionPageState();
}

class _WrongQuestionPageState extends State<WrongQuestionPage>
    with TickerProviderStateMixin {
  late BuildContext _context;

  /// tabBar控制器
  late TabController _tabController;

  /// tabBar相关数据
  late List<ColumnModel> _tabList;

  @override
  void initState() {
    super.initState();
    debugPrint("wrongQuestionPage 页面 -> initState 方法执行 ===> ");

    _tabList = [ColumnModel(name: "最新错题", type: ColumnTypeEnum.zx)];
    List<ColumnModel> list = dataUtilComm.dataModel.myList;
    _tabList.addAll(list);
    _tabController = TabController(length: _tabList.length, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("wrongQuestionPage 页面 -> dispose 方法执行 ===> ");
    _tabController.dispose();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("wrongQuestionPage 页面 -> build 方法执行 ===> ");

    _context = context;
    return Scaffold(
      backgroundColor: colorWhite1,
      body: SafeArea(child: Column(
        children: [
          PageTitleWidget(
            name: "我的错题",
            pageContext: context,
            rightShow: true,
            rightFun: _onTapFunYjqc,
          ),
          MyTabBarWidget(
            tabController: _tabController,
            list: _tabList,
          ),
          Expanded(child: _bottomItem()),
        ],
      )),
    );
  }

  /// 底部组件显示
  _bottomItem() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 24),
      child: Column(
        children: [
          _bottomTips(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: _viewItems(),
            ),
          ),
        ],
      ),
    );
  }

  /// 底部页面提示
  _bottomTips() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 28),
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: colorYellow5,
        borderRadius: BorderRadius.all(Radius.circular(28)),
      ),
      child: Row(
        children: [
          SvgPicture.asset(
            "images/my/wrong_question.svg",
            width: 30,
            height: 30,
          ),
          hiSpace(width: 4),
          Padding(
            padding: EdgeInsets.only(bottom: 3),
            child: Text(
              "错题答对自动移除错题记录",
              style: FontUtil.fontOrange12(20),
            ),
          ),
        ],
      ),
    );
  }

  /// 页面显示
  _viewItems() {
    List<Widget> pageList = [];
    for (ColumnModel model in _tabList) {
      if (model.type == ColumnTypeEnum.zx) {
        pageList.add(ViewPage(tabModel: model, type: RankTypeEnum.error));
      } else if (model.type == ColumnTypeEnum.chapterPractice) {
        // 章节页面
        pageList.add(ViewChapterPage(
          tabModel: model,
          rankType: RankTypeEnum.error,
        ));
      } else if (model.type == ColumnTypeEnum.paperLibrary) {
        // 试卷页面
        pageList.add(ViewPaperPage(
          tabModel: model,
          rankType: RankTypeEnum.error,
        ));
      }
    }
    return pageList;
  }

  /// 一键清除按钮点击方法
  _onTapFunYjqc() async {
    bool? del = await _showDialogYjqc();
    debugPrint("一键清除对话框返回值 ===> $del");
    if (del == null) {
      // 取消
    } else {
      // 确认删除
      _delWrong();
    }
  }

  /// 弹出对话框方法
  Future<bool?> _showDialogYjqc() {
    return showDialog<bool>(
      context: _context,
      builder: (context) {
        return AlertDialog(
          title: Text(
            "清除错题记录",
            style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
            textAlign: TextAlign.center,
          ),
          content: Text(
            "确定一键清除该科目下所有错题吗?",
            style: FontUtil.fontGrey1(28),
            textAlign: TextAlign.center,
          ),
          titlePadding: EdgeInsets.only(top: 28),
          contentPadding: EdgeInsets.only(left: 28, right: 28, top: 28),
          backgroundColor: colorWhite1,
          surfaceTintColor: colorWhite1,
          actionsPadding: EdgeInsets.zero,
          actionsAlignment: MainAxisAlignment.spaceAround,
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(
                "取消",
                style: FontUtil.fontGrey1(28),
              ),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              child: Text(
                "确定",
                style: FontUtil.fontRed2(28),
              ),
            ),
          ],
        );
      },
    );
  }

  /// 清除做题记录方法
  void _delWrong() {
    // 打开加载框
    ToastUtil.loadingBoxShow(_context);
    // 发送请求
    MyDao.delCategoryError(
      industryCode: dataUtilComm.dataModel.industryId,
      examId: dataUtilComm.dataModel.examId,
      categoryId: dataUtilComm.dataModel.categoryId,
    ).then((value) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      eventBus.fire(EventWrongCollectDelete());
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();

      String msg = "未知错误，请重试";
      if (e is DaoException) {

        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }
}
